package com.zy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.entity.Department;
import com.zy.entity.User;
import com.zy.mapper.ZyDepartMapper;
import com.zy.mapper.ZyDepartUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 杨深俊
 * @Date: 2021/04/14/13:17
 * @Description:
 */
@Controller
public class ZyDepartController {
    @Autowired
    public ZyDepartUserMapper zyDepartUserMapper;
    @Autowired
    public ZyDepartMapper zyDepartMapper;

    @RequestMapping("/departManage")
    public ModelAndView getDepart(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "7") Integer pageSize) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("DepartManage");

        //分页
        IPage<Department> iPage = new Page<>(pageNum, pageSize);
        IPage<Department> departs = zyDepartMapper.selectPage(iPage, null);
        //查询所有用户
        List<User> users = zyDepartMapper.getUsers();
        List<Department> departments = zyDepartMapper.getDeparts();

        modelAndView.addObject("departs", departs);
        modelAndView.addObject("users", users);
        modelAndView.addObject("departments", departments);
        return modelAndView;
    }

    //添加部门
    @PostMapping("addDepart")
    public String addDepart(@ModelAttribute Department department, Integer pageNum) {
        zyDepartMapper.insert(department);
        return "redirect:departManage?pageNum=" + pageNum;
    }

    //删除部门
    @RequestMapping("/delDepart")
    public String delDepart(Integer id) {
        zyDepartMapper.delDepartsById(id);
        zyDepartMapper.delDepartById(id);
        return "redirect:departManage";
    }

    //修改部门信息
    @PostMapping("/updateDepart")
    public String updateDepart(@ModelAttribute Department department, Integer pageNum) {
        zyDepartMapper.updateDepart(department);
        return "redirect:/departManage?pageNum=" + pageNum;
    }

    @GetMapping("/getDepart")
    @ResponseBody
    public Department getDepart(Integer id) {
        Department department = zyDepartMapper.selectDepart(id);
        System.out.println(department);
        return department;
    }
}
